package com.example.user.service.Impl;

import com.example.model.check_in.PasswordDo;
import com.example.user.domain.LoginUser;
import com.example.user.mapper.UserMapper;
import com.example.user.utils.TokenWorker;
import com.example.user.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenWorker tokenWorker;

    @Override
    public String login(String username, String password) throws AuthenticationException {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenWorker.generateToken(loginUser);
    }

    @Override
    public Boolean hasPerm(String permission, LoginUser loginUser) {
        return loginUser.getAuthorities().stream()
                .anyMatch(authority -> authority.getAuthority().equals(permission));
    }

    @Override
    public String getLoginUsername(LoginUser loginUser) {
        return loginUser.getUsername();
    }

}
